package router

// 只负责初始化路由的处理

import (
	"context"
	"fmt"
	"net/http"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

type IFnRegisterRoute = func(rgPublic *gin.RouterGroup, rgAuth *gin.RouterGroup)

var (
	gfnRouters []IFnRegisterRoute //收集路由信息
)

func RegisterRoute(fn IFnRegisterRoute) {
	if fn == nil {
		return
	}
	gfnRouters = append(gfnRouters, fn)
}

func InitRouter() {
	ctx, cancelCtx := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGALRM)
	defer cancelCtx()

	r := gin.Default() //初始化默认gin

	rgPublic := r.Group("/api/v1/public") //无需鉴权
	rgAuth := r.Group("/api/v1")          //需鉴权

	InitBasePlatformRoutes()

	for _, fnRegistRoute := range gfnRouters {
		fnRegistRoute(rgPublic, rgAuth)
	}

	port := viper.GetString("server.port")
	if port == "" {
		port = "8999"
	}

	server := &http.Server{
		Addr:    fmt.Sprintf(":%s", port),
		Handler: r,
	}

	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			// TODO : 记录日志
			fmt.Println(fmt.Sprintln("Start Server Error : %s", err.Error()))
		}

		fmt.Println(fmt.Sprintln("Start Server Listen: %s", port))
	}()

	<-ctx.Done()
	ctx, cancelShotdown := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelShotdown()
	if err := server.Shutdown(ctx); err != nil {
		// 记录日志
		fmt.Println("Stop Server Error : %s", err.Error())
		return
	}
	fmt.Println("stop server Success")
}

func InitBasePlatformRoutes() { //初始化基础平台的路由
	InitUserRoutes()
}
